using System.Text.Json;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Infrastructure.Configurations;

namespace UniversalAdmin.Infrastructure.Services;

public class KimiEmbeddingService : IEmbeddingService
{
    private readonly HttpClient _httpClient;
    private readonly KimiConfig _config;
    private readonly ILogger<KimiEmbeddingService> _logger;

    public KimiEmbeddingService(
        HttpClient httpClient,
        IOptions<KimiConfig> config,
        ILogger<KimiEmbeddingService> logger)
    {
        _httpClient = httpClient;
        _config = config.Value;
        _logger = logger;
    }

    public async Task<float[]> GenerateEmbeddingAsync(string text, bool isQuery = false)
    {
        try
        {
            var request = new
            {
                model = _config.EmbeddingModel,
                input = text
            };

            var content = JsonSerializer.Serialize(request);
            // 使用配置的嵌入服务端点
            var embeddingUrl = _config.EmbeddingUrl;
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, embeddingUrl)
            {
                Content = new StringContent(content, System.Text.Encoding.UTF8, "application/json")
            };

            // 添加认证头
            requestMessage.Headers.Add("Authorization", $"Bearer {_config.ApiKey}");

            var response = await _httpClient.SendAsync(requestMessage);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseObj = JsonSerializer.Deserialize<JsonElement>(responseContent);

            if (responseObj.TryGetProperty("data", out var dataElement) &&
                dataElement.ValueKind == JsonValueKind.Array &&
                dataElement.GetArrayLength() > 0)
            {
                var firstItem = dataElement[0];
                if (firstItem.TryGetProperty("embedding", out var embeddingElement) &&
                    embeddingElement.ValueKind == JsonValueKind.Array)
                {
                    return embeddingElement.EnumerateArray().Select(x => x.GetSingle()).ToArray();
                }
            }

            _logger.LogError("Failed to generate embedding: {Response}", responseContent);
            throw new Exception("Failed to generate embedding");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating embedding for text: {Text}", text);
            throw;
        }
    }

    public async Task<List<float[]>> GenerateEmbeddingsAsync(List<string> texts, bool isQuery = false)
    {
        var embeddings = new List<float[]>();

        foreach (var text in texts)
        {
            var embedding = await GenerateEmbeddingAsync(text, isQuery);
            embeddings.Add(embedding);
        }

        return embeddings;
    }
}